#include "aht21.h"

#define AHT21_ADDRESS 0x70
uint8_t readBuff[6] = {0};
void AHT21_Init(void)
{
    uint8_t readBuff;
    HAL_Delay(100);
    HAL_I2C_Master_Receive(&hi2c1, AHT21_ADDRESS, &readBuff, 1, HAL_MAX_DELAY);
    if ((readBuff & 0x18) != 0x18)
    {
        uint8_t sendBuff[3] = {0x1B, 0x1C, 0x1E};
        HAL_I2C_Master_Transmit(&hi2c1, AHT21_ADDRESS, (uint8_t *)sendBuff, 3, HAL_MAX_DELAY);
    }
}

void AHT21_Read(float *Temperature, float *Humidity)
{
    uint8_t sendBuff[3] = {0xAC, 0x33, 0x00};
    HAL_I2C_Master_Transmit(&hi2c1, AHT21_ADDRESS, (uint8_t *)sendBuff, 3, HAL_MAX_DELAY);
    HAL_Delay(75);
    HAL_I2C_Master_Receive(&hi2c1, AHT21_ADDRESS, (uint8_t *)readBuff, 6, HAL_MAX_DELAY);
    if ((readBuff[0] & 0x80) == 0x00)
    {
        uint32_t data = 0;
        data = ((uint32_t)readBuff[1] << 12) | ((uint32_t)readBuff[2] << 4) | ((uint32_t)readBuff[3] >> 4);
        *Humidity = data * 100.0f / (1 << 20);
        // *Humidity = data / 1048576.0 * 100.0;
        data = (((uint32_t)readBuff[3] & 0x0F) << 16) | ((uint32_t)readBuff[4] << 8) | (uint32_t)readBuff[5];
        // *Temperature = data * 200.0f / (1 << 20) - 50;
        *Temperature = (data / 1048576.0 * 200) - 50;
    }
}
//
void AHT21_Measure(void)
{
    static uint8_t sendBuff[3] = {0xAC, 0x33, 0x00};
    HAL_I2C_Master_Transmit(&hi2c1, AHT21_ADDRESS, (uint8_t *)sendBuff, 3, HAL_MAX_DELAY);
}

void AHT21_Get(void)
{
    HAL_I2C_Master_Receive(&hi2c1, AHT21_ADDRESS, (uint8_t *)readBuff, 6, HAL_MAX_DELAY);
}

void AHT21_Analysis(float *Temperature, float *Humidity)
{
    if ((readBuff[0] & 0x80) == 0x00)
    {
        uint32_t data = 0;
        data = ((uint32_t)readBuff[3] >> 4) + ((uint32_t)readBuff[2] << 4) + ((uint32_t)readBuff[1] << 12);
        //			 *Humidity = data * 100.0f / (1 << 20);
        *Humidity = data / 1048576.0;
        data = (((uint32_t)readBuff[3] & 0x0F) << 16) + ((uint32_t)readBuff[4] << 8) + (uint32_t)readBuff[5];
        //        *Temperature = data * 200.0f / (1 << 20) - 50;
        *Temperature = (data / 1048576.0 * 200) - 50;
    }
}
